package pers.yaoliguo.bms.uitl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


/**
 * @ClassName:       EhcacheUtil
 * @Description:    TODO
 * @author:            yao
 * @date:            2017年6月24日        下午6:19:57
 */
public class EhcacheUtil {
	
	private static final String path = "/ehcache.xml";
	private URL url;
	private CacheManager manager;
	private static EhcacheUtil ehCache;
	
	public static final String MY_CACHE = "myCache";
	
	public static final String MENU_CACHE = "MenuCache";
	
	private EhcacheUtil(String path) { 
		url = getClass().getResource(path); 
		manager = CacheManager.create(url); 
		System.setProperty(net.sf.ehcache.CacheManager.ENABLE_SHUTDOWN_HOOK_PROPERTY, "true");
    }
	
	public static EhcacheUtil getInstance(){
		if (ehCache == null) {
			ehCache = new EhcacheUtil(path);
		}
		return ehCache;
	}
	
	public void put(String cacheName, String key, Object value) { 
		Cache cache = manager.getCache(cacheName); 
		Element element = new Element(key, value); 
		cache.put(element); 
	}
	
	public Object get(String cacheName, String key) { 
		Cache cache = manager.getCache(cacheName); 
		Element element = cache.get(key); 
		return element == null ? null : element.getObjectValue(); 
	}
	
	public List<Object> getValues(String cacheName){
		Cache cache = manager.getCache(cacheName);
		
		List<Object> list = new ArrayList<Object>();
		List<String> keys = cache.getKeys();
		for (String key : keys) {
			Element element = cache.get(key);
			if (element != null && element.getObjectValue() != null) {
				list.add(element.getObjectValue());
			}
		}
		//将缓存数据写入到磁盘，当项目重启时读取磁盘中的数据
		cache.flush();
		return list;
	}
	
	public void remove(String cacheName, String key) { 
		Cache cache = manager.getCache(cacheName); 
		cache.remove(key);
	}
	
	public void removeAll(String cacheName){
		Cache cache = manager.getCache(cacheName);
		cache.removeAll();
	}

	public CacheManager getManager() {
		return manager;
	}

	public void setManager(CacheManager manager) {
		this.manager = manager;
	}

}
